
$(document).ready(function() {
	loadFolder();
});

function loadFolder(folder, isFull) {
	if (folder === undefined) {
		folder = $('input.current_folder').val();
	} else if (folder === -1) {
		folder = $('input.parent_folder').val();
	} else if (isFull !== true) {
		folder = $('input.current_folder').val() + '/' + folder;
	}
	
	var folder = folder;
	
	$.ajax ({
		url: baseURI + '/admin/filemanager/ajax_files?folder='+folder,
		dataType: 'xml',
		type: 'get',
		error: function () { alert("Ошибка при загрузке списка файлов!");  },
		success: function (xml) {
			
			$('input.current_folder').val($(xml).find('folder').attr('path'));
			$('input.parent_folder').val($(xml).find('folder').attr('parent'));
			$('#filemanager_wrapper').html('');
			
			$(xml).find('file').each(function() {
				var name = $(this).attr('name');
				var dir = $(this).attr('dir') == 1 ? true : false;
				var ext = $(this).find('extension').text();
				var size = (Math.round(($(this).find('size').text() / 1024) * 100) / 100) + ' Кб';
				var mtime = $(this).find('mtime').text();
				var perms = $(this).find('perms').text();
				var permsNum = $(this).find('perms').attr('num');
				
				if (dir) {
					$('#filemanager_wrapper').append(
						$('<tr>').html(
							'<td class="checkboxTd"><input type="checkbox" name="delete[]" value="'+name+'" /></td>'+
							"<td>"+
								'<img src="'+baseURI+'/images/filemanager/folder.png" /> <a class="mainlink" href="#" onclick="loadFolder(\''+name+'\'); return false;">'+name+"</a></td>"+
							"<td></td>"+
							"<td></td>"+
							"<td>"+
								'<a href="#" onclick="editPerms(\''+name+'\', \''+permsNum+'\'); return false;" title="Редактировать">'+perms+'</a>'+
							"</td>"+
							"<td>"+
								'<a href="#" onclick="rename(\''+name+'\'); return false;" title="Переименовать"><img src="'+baseURI+'/images/filemanager/rename.png" /></a>'+
							"</td>")
					);
				} else {
					switch (ext) {
						case 'txt' : var fileIcon = 'txt'; break;
						case 'php' : var fileIcon = 'php'; break;
						case 'gif' :
						case 'jpg' :
						case 'png' : var fileIcon = 'img'; break;
						case 'pdf' : var fileIcon = 'pdf'; break;
						case 'sql' : var fileIcon = 'sql'; break;
						case 'html' : var fileIcon = 'html'; break;
						case 'css' : var fileIcon = 'css'; break;
						case 'js' : var fileIcon = 'js'; break;
						default : var fileIcon = 'file';
					}
					
					$('#filemanager_wrapper').append(
						$('<tr>').html(
							'<td class="checkboxTd"><input type="checkbox" name="delete[]" value="'+name+'" /></td>'+
							"<td>"+
								'<img src="'+baseURI+'/images/filemanager/'+fileIcon+'.png" /> '+name+"</td>"+
							"<td>"+size+"</td>"+
							"<td>"+mtime+"</td>"+
							"<td>"+
								'<a href="#" onclick="editPerms(\''+name+'\', \''+permsNum+'\'); return false;" title="Редактировать">'+perms+'</a>'+
							"</td>"+
							"<td>"+
								'<a href="#" onclick="rename(\''+name+'\'); return false;" title="Переименовать"><img src="'+baseURI+'/images/filemanager/rename.png" /></a>'+
							"</td>")
					);
				}
			});
			
			buildFolderPath();			
			hightlightTableRows();
		}
	});
}

function buildFolderPath() {
	var folder = $('input.current_folder').val();
	
	if (folder == '') {
		$('#folder_path').html('<div class="item">Начало</div>');
	} else {
		var parts = folder.split('/');
		
		var html = '<a href="#" onclick="loadFolder(\'\', true); return false;" class="item">Начало</a><div class="separator">›</div>';
		var dump = '';
		
		for(i = 0; i < parts.length; ++i) {
			dump += parts[i]+'/';
					
			if (i+1 == parts.length) {
				html += '<div class="item">'+parts[i]+'</div>';
			} else {
				html += '<a href="#" onclick="loadFolder(\''+dump+'\', true); return false;" class="item">'+parts[i]+'</a><div class="separator">›</div>';
			}
		}
		
		$('#folder_path').html(html);
	}
}

function addFileUpload(button) {
	$(button).remove();
	var fileInput = $('<input>').attr('name', 'upload[]');
	
	$('#files_upload_fields').append(
		$('<p>')
			.append($('<input>').attr({type: 'file', name: 'upload[]'}))
			.append($('<span>').html('&nbsp;'))
			.append($('<input>').attr('type','button').val('+').click(function() { addFileUpload(this); }))
	);
}

function editPerms(name, val) {
	var div = $('<div>').html(
		'<div class="p"><form action="'+baseURI+'/admin/filemanager/js_action" method="post" target="backframe_rename">'+
			'<input type="hidden" name="folder" value="'+$('input.current_folder').val()+'" />'+
			'<input type="hidden" name="name" value="'+name+'" />'+
			'<input type="test" name="perms" value="'+val+'" /> '+
			'<input type="submit" name="button_perms" value="Сохранить права" />'+
		'</form></div>'+
		'<iframe name="backframe_rename" style="display:none" src="about:blank" width="1" height="1"></iframe>'
	);
	
	showDialog(div);
}

function filemanagerPermsError() {
	new Error('Невозможно выставить права!');
}

function filemanagerPermsSaved() {
	new Message('Права сохранены!');
	hideDialog();
	loadFolder();
}

function rename(name) {
	var div = $('<div>').html(
		'<div class="p"><form action="'+baseURI+'/admin/filemanager/js_action" method="post" target="backframe_rename">'+
			'<input type="hidden" name="folder" value="'+$('input.current_folder').val()+'" />'+
			'<input type="hidden" name="old_name" value="'+name+'" />'+
			'<input type="test" name="new_name" value="'+name+'" /> '+
			'<input type="submit" name="button_rename" value="Переименовать" />'+
		'</form></div>'+
		'<iframe name="backframe_rename" style="display:none" src="about:blank" width="1" height="1"></iframe>'
	);
	
	showDialog(div);
}

function filemanagerRenameError() {
	new Error('Невозможно переименовать!');
}

function filemanagerRenamed() {
	new Message('Файл переименован!');
	hideDialog();
	loadFolder();
}

function filemanagerFilesDeleted() {
	new Message('Файлы удалены!');
	loadFolder();
}

function filemanagerUploadError() {
	new Error('Файлы не загружены!');
}

function filemanagerFilesUploaded() {
	new Message('Файлы загружены!');
	
	$('#files_upload_fields')
		.empty()
		.append(
			$('<p>')
				.append($('<input>').attr({type: 'file', name: 'upload[]'}))
				.append($('<span>').text(' '))
				.append($('<input>').attr('type','button').val('+').click(function() { addFileUpload(this); }))
	);
	
	loadFolder();
}

function filemanagerZipError() {
	new Error('Архив не загружен!');
}

function filemanagerZipUploaded() {
	new Message('Архив распакован!');
	
	$('#zip_upload_field').replaceWith($('<input>').attr({type: 'file', name: 'zip', id: 'zip_upload_field'}));
	
	loadFolder();
}

function filemanagerFolderExists() {
	new Error('Папка с таким названием уже существует');
}

function filemanagerFolderCreated() {
	new Message('Папка создана!');
	
	$('#new_folder_name_field').val('');
	
	loadFolder();	
}